package com.itheima.servlet;

import com.itheima.domain.User;
import com.itheima.service.Service;
import com.itheima.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
    private Service service = new UserServiceImpl();
    public void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<User> list = service.findAll();
        req.setAttribute("list",list);
        resp.setContentType("text/html;charset=UTF-8");
        req.getRequestDispatcher("/WEB-INF/pages/User_List.jsp").forward(req,resp);
    }

    public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/pages/User_Add.jsp").forward(req,resp);
    }

    public void insertInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String email = req.getParameter("email");
        User user = new User();
        user.setUsername(username);
        user.setEmail(email);
        service.insertInfo(user);
        resp.sendRedirect(req.getContextPath() + "/user/findAll");
    }

    public void beforeUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        User user = service.findById(Integer.parseInt(id));
        req.setAttribute("user",user);
        req.getRequestDispatcher("/WEB-INF/pages/User_Update.jsp").forward(req,resp);
    }

    public void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        String username = req.getParameter("username");
        String email = req.getParameter("email");
        User user = new User(Integer.parseInt(id),username,email);
        service.update(user);
        resp.sendRedirect(req.getContextPath() + "/user/findAll");
    }

    public void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        service.delete(Integer.parseInt(id));
        resp.sendRedirect(req.getContextPath() + "/user/findAll");
    }

}
